<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\AdminUserModel;
use App\Models\CompanyManagementModel;
use App\Models\DepartmentManagementModel;
use App\Models\PostManagementModel;
use App\Models\StaffManagementModel;

class MailListController extends Controller
{
    //通讯录
    public function index()
    {
        $staffs = StaffManagementModel::where('admin_user_id', '!=', auth('api')->user()->id)->where('company_id', auth('api')->user()->company_id)->get()->map(function ($item) {
            $avatar = AdminUserModel::where('id', $item->admin_user_id)->value('avatar');
            return ['id' => $item->id, 'avatar' => empty($avatar) ? url('/vendor/laravel-admin/AdminLTE/dist/img/user2-160x160.jpg') : url($avatar), 'name' => $item->name, 'py_name' => $item->py_name, 'mobile' => $item->mobile, 'department_id' => $item->department_id, 'post_id' => $item->post_id, 'post_name' => $item->post_name];
        });
        $az = [];
        for ($i = 65; $i < 91; $i++) {
            $letter = strtoupper(chr($i));
            $data = [];
            foreach ($staffs as $staff) {
                if ($staff['py_name'] == $letter) {
                    $data[] = $staff;
                }
            }
            $az[$letter] = $data;
        }

        return $this->return_data([
            //公司名称
            'company_name' => CompanyManagementModel::where('id', auth('api')->user()->company_id)->value('company_name'),
            //公司所有部门和岗位
            'departments' => DepartmentManagementModel::where('company_id', auth('api')->user()->company_id)->get()->map(function ($item) {
                return ['id' => $item->id, 'name' => $item->department_name, 'post_sons' => PostManagementModel::where('department_id', $item->id)->get()->map(function ($item) {
                    return ['id' => $item->id, 'name' => $item->post_name];
                })];
            }),
            //公司所有员工
            'staffs' => $az
        ]);
    }
}
